import { CssVarsProvider, StyledEngineProvider, Textarea } from "@mui/joy";
import {
  Box,
  Chip,
  FormControl,
  Grid,
  InputLabel,
  Link,
  MenuItem,
  Paper,
  TextField,
  Typography,
  useTheme,
} from "@mui/material";
import { DatePicker, DesktopDatePicker } from "@mui/x-date-pickers";
import { useMutation } from "@tanstack/react-query";
import { useSnackbar } from "notistack";
import React, { useMemo, useState } from "react";
import { useEffect } from "react";
import { useContext } from "react";
import { ThemeColorContext, UserProContext } from "../../../App";
import CommentArea from "../../../components/CommentArea";
import Dataform from "../../../components/Dataform";
import LoadingButton from "../../../components/LoadingButton";
import MyTextarea from "../../../components/MyTextArea";
import { COMPETITON_URL } from "../../../constants/url";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import { TitleContext } from "../../../router";
import GetChipType from "./GetChipType";
import moment from "moment/moment";
import GetDetail from "./GetDetail";
import { renderCellExpand } from "../../../components/RenderCellExpand";
import Select from "@mui/material/Select";
const UrlRender = (param) => {
  return (
    <Link target="_blank" href={param.value} underline="none">
      论文链接
    </Link>
  );
};
export default function StudentWork() {
  const titleContext = useContext(TitleContext);
  useEffect(() => {
    titleContext.setnowTitle(13);
  }, []);
  const columns = [
    {
      field: "id",
      headerName: "序号",
      flex: 1,
      editable: false,
    },
    {
      field: "name",
      headerName: "比赛名称",
      flex: 4,
      renderCell: renderCellExpand,
    },
    {
      field: "time",
      type: "dateTime",
      headerName: "比赛时间",
      // flex: 4,
      width: 150,
    },
    {
      field: "score",
      headerName: "综评分",
      flex: 1,
    },
    {
      field: "awardLevel",
      headerName: "等级",
      flex: 2,
    },
    {
      field: "awardUnit",
      headerName: "颁奖单位",
      renderCell: renderCellExpand,
      flex: 3,
    },
    {
      field: "detail",
      headerName: "备注",
      hideable: false,
      width: 120,
      renderCell: GetDetail,
    },
    {
      field: "status",
      headerName: "状态",
      renderCell: GetChipType,
      flex: 2,
    },
  ];

  const {
    isLoading: updLoading,
    isSuccess: updSuccess,
    data: upddata,
    isError: updError,
    mutate: updMutate,
  } = useMutation(["updStudentwork"], mutateQueryFn);

  const {
    data,
    isLoading: getLoading,
    mutate: getMutate,
    isSuccess: getSuccess,
  } = useMutation(["getStudentwork"], mutateQueryFn);

  useEffect(() => {
    getMutate({ url: COMPETITON_URL, method: "get", useToken: true });
  }, []);
  const userProContext = useContext(UserProContext);

  const [newItem, setNewItem] = useState({ score: 0 });
  const [rows, setRows] = useState([]);
  useEffect(() => {
    if (getSuccess) {
      setRows(
        data.data.data.map((val, key) => {
          return {
            ...val,
            id: key + 1,
          };
        })
      );
    }
  }, [getSuccess]);

  const handleUpd = () => {
    if (!newItem?.name) {
      enqueueSnackbar("奖项名称不能为空", { variant: "warning" });
      return;
    }
    if (!newItem?.time) {
      enqueueSnackbar("请选择获奖时间", { variant: "warning" });
      return;
    }
    if (!newItem?.awardLevel) {
      enqueueSnackbar("请选择奖项等级", { variant: "warning" });
      return;
    }
    // if (!newItem?.detail) {
    //   enqueueSnackbar("请填写详情", { variant: "warning" });
    //   return;
    // }
    if (!newItem?.awardUnit) {
      enqueueSnackbar("请填写颁奖单位", { variant: "warning" });
      return;
    }
    updMutate({
      url: COMPETITON_URL,
      method: "put",
      data: {
        ...newItem,
        time: moment(newItem.time.toString()).format("YYYY-MM-DD"),
      },
      useToken: true,
    });
  };
  const [updbutSuccess, setUpdSuccess] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  useEffect(() => {
    if (updSuccess) {
      if (upddata.data.code != 0) {
        enqueueSnackbar(upddata.data.data, { variant: "error" });
      } else {
        setNewItem({ score: 0 });
        enqueueSnackbar("提交成功", { variant: "success" });
        getMutate({ url: COMPETITON_URL, method: "get", useToken: true });
        setUpdSuccess(true);
        setTimeout(() => {
          setUpdSuccess(false);
        }, 1500);
      }
    }
  }, [updSuccess]);

  return (
    <div>
      <Grid container spacing={3}>
        <Grid item xs={4} md={12} lg={4} sm={12}>
          <Paper sx={{ padding: "20px 20px", marginBottom: 2 }}>
            <Typography sx={{ marginBottom: 3 }} variant="h5">
              竞赛经历申请
            </Typography>
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                // flexWrap: "wrap",
              }}
            >
              <Box flexGrow={1} sx={{ marginTop: 4 }}>
                <TextField
                  value={newItem.name}
                  onChange={(e) => {
                    setNewItem({ ...newItem, name: e.target.value });
                  }}
                  size="small"
                  label="比赛名称*"
                ></TextField>
              </Box>

              <Box flexGrow={1} sx={{ marginTop: 4 }}>
                <DesktopDatePicker
                  label="发表时间*"
                  disableFuture
                  value={newItem.time ?? null}
                  onChange={(newValue) => {
                    setNewItem({ ...newItem, time: newValue });
                  }}
                  renderInput={(params) => (
                    <TextField size="small" {...params} />
                  )}
                />
              </Box>
              <Box sx={{ marginTop: 4 }} flexGrow={1}>
                <FormControl>
                  <InputLabel id="demo-simple-select-autowidth-label">
                    获奖等级*
                  </InputLabel>
                  <Select
                    size="small"
                    autoWidth
                    sx={{ width: 100 }}
                    label="Age"
                    value={newItem.awardLevel}
                    onChange={(e) => {
                      setNewItem({ ...newItem, awardLevel: e.target.value });
                    }}
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                  >
                    {/* <MenuItem value={null}>请选择</MenuItem> */}
                    <MenuItem value={"国一"}>国一</MenuItem>
                    <MenuItem value={"国二"}>国二</MenuItem>
                    <MenuItem value={"国三"}>国三</MenuItem>
                    <MenuItem value={"省一"}>省一</MenuItem>
                    <MenuItem value={"省二"}>省二</MenuItem>
                    <MenuItem value={"省三"}>省三</MenuItem>
                    <MenuItem value={"其他"}>其他</MenuItem>
                  </Select>
                </FormControl>
              </Box>
              <Box sx={{ marginTop: 4 }} flexGrow={1}>
                <TextField
                  value={newItem.awardUnit}
                  onChange={(e) => {
                    setNewItem({ ...newItem, awardUnit: e.target.value });
                  }}
                  size="small"
                  label="颁奖单位*"
                ></TextField>
              </Box>
              <Box sx={{ marginTop: 3, width: "30%", minWidth: 300 }}>
                <MyTextarea
                  value={newItem.detail}
                  change={(e) => setNewItem({ ...newItem, detail: e })}
                  placeholder="备注"
                />
              </Box>
            </Box>
            <Box
              sx={{
                marginTop: 4,
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <LoadingButton
                titler={updbutSuccess ? "提交成功" : "提交申请"}
                clickr={handleUpd}
                isFetching={updLoading}
                isSuccess={updbutSuccess}
              />
            </Box>
          </Paper>
        </Grid>
        <Grid item xs={8} md={12} lg={8} sm={12}>
          <Dataform
            fileName={userProContext.userPro.name + " 竞赛经历"}
            rows={rows}
            loading={getLoading}
            columns={columns}
          />
        </Grid>
      </Grid>
      {/* )} */}
    </div>
  );
}
